<template>
  <div class="page">
    <div class="btns">
      <el-form ref="form" :inline="true" :model="form" label-width="80px">
        <el-form-item label="搜索内容">
          <el-input
            v-model="form.search"
            size="large"
            placeholder="管理员账号"
            @keypress="inputKey"
            clearable
            @clear="getList(1)"
            class="input"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="large" @click="getList(1)"
            >搜索</el-button
          >
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="itemAdd">添加管理员</el-button>
    </div>

    <el-table :data="tableData" class="table" border v-loading="loading">
      <el-table-column
        prop="admin_id"
        label="管理员ID"
        width="120"
        align="center"
      >
      </el-table-column>
      <el-table-column prop="admin_username" label="管理员名称" min-width="120">
      </el-table-column>
      <el-table-column prop="admin_account" label="管理员账号" min-width="120">
      </el-table-column>
      <el-table-column prop="role_name" label="角色" width="160" align="center">
        <template #default="{ row, $index }">
          <el-tag type="warning">{{
            row.role_id == 1
              ? "超级管理员"
              : ''
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="is_banned"
        label="账号状态"
        width="160"
        align="center"
      >
        <template #default="{ row, $index }">
          <el-text type="danger" v-if="row.is_banned == 1">禁用</el-text>
          <el-text type="success" v-if="row.is_banned == 2">启用</el-text>
        </template>
      </el-table-column>
      <el-table-column prop="is_banned" label="状态操作" width="160" align="center">
        <template #default="{row,$index}">
          <el-button type="danger" size="small" v-if="row.is_banned == 2"
            @click="itemBanned(row,1)">禁用</el-button>
          <el-button type="success" size="small" v-if="row.is_banned == 1"
            @click="itemBanned(row,2)">启用</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间"> </el-table-column>
      <el-table-column prop="updated_at" label="修改时间"> </el-table-column>

      <el-table-column label="操作" fixed="right" width="180" align="center">
        <template #default="{ row, $index }">
          <el-link
            type="success"
            :underline="false"
            @click="itemEdit(row)"
            :disabled="row.listings_category_id < 4"
            >修改</el-link
          >
          <el-link
            type="warning"
            :underline="false"
            style="margin-left: 12px"
            @click="openResetPassword(row)"
            >重置密码</el-link
          >
          <el-link
            type="primary"
            :underline="false"
            style="margin-left: 12px"
            @click="openChangePassword(row)"
            >修改密码</el-link
          >
          <el-link
            type="danger"
            :underline="false"
            style="margin-left: 12px"
            :disabled="row.admin_id == 1"
            @click="itemRemove(row)"
            >删除</el-link
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        @size-change="sizeChange"
        @current-change="getList"
        :current-page="form.page"
        :page-sizes="[20, 50, 100, 200]"
        :page-size="form.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="count"
      >
      </el-pagination>
    </div>

    <el-drawer v-model="drawer" v-if="drawer" size="600" direction="rtl">
      <template #header>
        <h4>{{ editForm?.admin_id ? "修改管理员信息" : "添加管理员信息" }}</h4>
      </template>
      <template #default>
        <el-form
          :model="editForm"
          :rules="editFormRule"
          ref="editFormRule"
          v-if="editForm"
          label-width="auto"
          style="max-width: 600px"
        >
          <el-form-item label="管理员名称" prop="admin_username">
            <el-input
              v-model="editForm.admin_username"
              size="large"
              style="width: 300px"
              placeholder="请输入管理员名称"
            />
          </el-form-item>
          <el-form-item label="管理员账号" prop="admin_account">
            <el-input
              v-model="editForm.admin_account"
              size="large"
              style="width: 300px"
              placeholder="请输入管理员账号"
            />
          </el-form-item>
          <el-form-item label="性别" prop="admin_gender">
            <el-radio-group v-model="editForm.admin_gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="角色" prop="role_id">
            <el-select
              v-model="editForm.role_id"
              placeholder="请选择角色"
              size="large"
              style="width: 300px"
            >
              <el-option
                v-for="item in roleList"
                :key="item.role_id"
                :label="item.role_name"
                :value="item.role_id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
          v-if="!editForm?.admin_id"
            label="账号密码"
            prop="admin_password"
            :required="!editForm.admin_id"
          >
            <el-input
              v-model="editForm.admin_password"
              size="large"
              style="width: 300px"
              type="password"
              show-password
              :placeholder="
                '请输入账号密码' +
                (editForm.admin_id ? '(如不修改请勿填写)' : '')
              "
            />
          </el-form-item>
          <el-form-item
          v-if="!editForm?.admin_id"
            label="确认密码"
            prop="admin_confirm_password"
            :required="!editForm.admin_id"
          >
            <el-input
              v-model="editForm.admin_confirm_password"
              size="large"
              style="width: 300px"
              type="password"
              show-password
              placeholder="请再次输入密码"
            />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button type="success" v-if="editForm?.admin_id" @click="edit"
            >修改</el-button
          >
          <el-button type="primary" v-else @click="add">添加</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 修改密码对话框 -->
    <el-dialog v-model="passwordDialogVisible" title="修改密码" width="30%">
      <el-form
        :model="passwordForm"
        :rules="passwordFormRules"
        ref="passwordFormRef"
        label-width="120px"
      >
        <el-form-item label="旧密码" prop="old_admin_password">
          <el-input
            v-model="passwordForm.old_admin_password"
            type="password"
            show-password
            placeholder="请输入旧密码"
          />
        </el-form-item>
        <el-form-item label="新密码" prop="new_admin_password">
          <el-input
            v-model="passwordForm.new_admin_password"
            type="password"
            show-password
            placeholder="请输入新密码"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirm_admin_password">
          <el-input
            v-model="passwordForm.confirm_admin_password"
            type="password"
            show-password
            placeholder="请再次输入新密码"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmChangePassword">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import img from "@/assets/img/import.js";
import api from "@/request/api.js";
export default {
  data() {

    // 自定义密码验证规则
    const validatePassword = (rule, value, callback) => {
      if (!this.editForm.admin_id && !value) {
        callback(new Error('请输入密码'));
      } else if (this.editForm.admin_confirm_password && value !== this.editForm.admin_confirm_password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    
    const validateConfirmPassword = (rule, value, callback) => {
      if (!this.editForm.admin_id && !value) {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.editForm.admin_password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
 
    // 修改密码验证规则
    const validateNewPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入新密码'));
      } else if (this.passwordForm.confirm_admin_password && value !== this.passwordForm.confirm_admin_password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    
    const validateConfirmNewPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请再次输入新密码'));
      } else if (value !== this.passwordForm.new_admin_password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    
    return {
      img,
      form: {
        page: 1,
        size: 20,
        search: "",
      },
      tableData: [],
      count: 0,
      loading: false,
      editForm: null,
      drawer: false,
      roleList: [],
      areaList: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level } = node;
          api.common
            .getAreaList({
              parent_id: node.value || 0,
            })
            .then((res) => {
              resolve(
                res.data.content.data.map((item) => ({
                  value: item.district_id,
                  label: item.district_name,
                  leaf: level >= 1,
                }))
              );
            });
        },
      },
      editFormRule: {
        admin_username: [
          {
            required: true,
            message: "请输入管理员名称",
            trigger: "blur",
          },
        ],
        admin_account: [
          {
            required: true,
            message: "请输入管理员账号",
            trigger: "blur",
          },
        ],
        admin_gender: [
          {
            required: true,
            message: "请选择性别",
            trigger: "change",
          },
        ],
        admin_password: [
          {
            validator: validatePassword,
            trigger: "blur",
          },
        ],
        admin_confirm_password: [
          {
            validator: validateConfirmPassword,
            trigger: "blur",
          },
        ],
      },
      passwordDialogVisible: false,
      passwordForm: {
        admin_id: '',
        old_admin_password: '',
        new_admin_password: '',
        confirm_admin_password: ''
      },
      passwordFormRules: {
        old_admin_password: [
          { required: true, message: "请输入旧密码", trigger: "blur" }
        ],
        new_admin_password: [
          { validator: validateNewPassword, trigger: "blur" }
        ],
        confirm_admin_password: [
          { validator: validateConfirmNewPassword, trigger: "blur" }
        ]
      },
      jiaoanList: [],
      currentAdmin: null // 当前操作的管理员
    };
  },
  created: function () {
    this.getList();
  },
  methods: {
    // 确认修改密码
    confirmChangePassword() {
      this.$refs.passwordFormRef.validate((valid) => {
        if (valid) {
          this.$request.admin.adminChangePassword({
            admin_id: this.passwordForm.admin_id,
            old_admin_password: this.passwordForm.old_admin_password,
            new_admin_password: this.passwordForm.new_admin_password,
            confirm_admin_password: this.passwordForm.confirm_admin_password
          }).then(res => {
            if (res.data.code === 200) {
              this.$message.success('密码修改成功');
              this.passwordDialogVisible = false;
            } else {
              this.$message.error(res.data.message || '密码修改失败');
            }
          }).catch(error => {
            this.$message.error('请求失败');
          });
        } else {
          return false;
        }
      });
    },
    // 重置密码
    openResetPassword(row) {
      this.$confirm('确定要重置该管理员的密码吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$request.admin.adminResetPassword({
          admin_id: row.admin_id
        }).then(res => {
          if (res.data.code === 200) {
            this.$message.success('密码重置成功');
          } else {
            this.$message.error(res.data.message || '密码重置失败');
          }
        });
      }).catch(() => {
        this.$message.info('已取消重置');
      });
    },
    // 打开修改密码对话框
    openChangePassword(row) {
      this.currentAdmin = row;
      this.passwordForm = {
        admin_id: row.admin_id,
        old_admin_password:'',
        new_admin_password: '',
        confirm_admin_password: ''
      };
      this.passwordDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.passwordFormRef?.resetFields();
      });
    },
    changeArea(obj) {
      console.log("areaObj", obj);
      this.editForm.area_id = 0;
      this.editForm.province_id = obj[0];
      this.editForm.city_id = obj[1];
    },
    getjiaoanList() {
      api.renwu.getList({ size: 99999 }).then((res) => {
        if (res.data.code == 200) {
          this.jiaoanList = res.data.content.data;
        }
      });
    },
    sizeChange(size) {
      this.form.size = size;
      this.getList(1);
    },
    itemBanned(item, is_banned) {
      this.$request.admin
        .adminIsBannedEdit({
          admin_id: item.admin_id,
          is_banned,
        })
        .then((res) => {
          if (res && res.data.code == 200) {
            this.getList();
          }
        });
    },
    itemAdd() {
      this.getRoleList();
      this.editForm = {
        admin_username: "",
        admin_account: "",
        admin_password: "",
        admin_confirm_password: "",
        admin_gender: 0,
        role_id: 1, 
      };
      this.drawer = true;
      this.$nextTick(() => {
        this.$refs.editFormRule?.resetFields();
      });
    },
    add() {
      this.$refs.editFormRule.validate((valid, fields) => {
        if (valid) {
          // 移除不需要的字段
          const { admin_confirm_password, ...rest } = this.editForm;
          
          this.$request.admin
            .adminInfoCreate({
              ...rest,
              admin_password: this.editForm.admin_password || "",
              admin_confirm_password: this.editForm.admin_password,
            })
            .then((res) => {
              if (res.data?.code == 200) {
                this.$message.success("添加成功");
                this.getList();
                this.drawer = false;
              }
            });
        } else {
          console.log("error submit!", fields);
        }
      });
    },
    itemEdit(item) {
      this.getRoleList();
      this.editForm = {
        admin_id: item.admin_id,
        admin_username: item.admin_username,
        admin_account: item.admin_account,
        admin_password: "",
        admin_confirm_password: "",
        admin_gender: item.admin_gender,
        role_id: item.role_id,
      };
      this.drawer = true;
      this.$nextTick(() => {
        this.$refs.editFormRule?.resetFields();
      });
    },
    edit() {
      this.$refs.editFormRule.validate((valid, fields) => {
        if (valid) {
          const submitData = {
            admin_id: this.editForm.admin_id,
            admin_username: this.editForm.admin_username,
            admin_account: this.editForm.admin_account,
            admin_gender: this.editForm.admin_gender,
            role_id: this.editForm.role_id,
          };
          
          // 只有当密码不为空时才添加密码字段
          if (this.editForm.admin_password) {
            submitData.admin_password = this.editForm.admin_password;
            submitData.admin_confirm_password = this.editForm.admin_password;
          }
          
          this.$request.admin
            .adminInfoUpdate(submitData)
            .then((res) => {
              if (res.data?.code == 200) {
                this.$message.success("修改成功");
                this.getList();
                this.drawer = false;
              }
            });
        } else {
          console.log("error submit!", fields);
        }
      });
    },
    itemRemove(item) {
      this.$confirm("确定删除此管理员？")
        .then((_) => {
          this.$request.admin
            .adminInfoDelete({
              admin_id: item.admin_id,
            })
            .then((res) => {
              if (res && res.data.code == 200) {
                this.$message.success("已删除");
                this.getList();
              } else {
                // this.$message.error(res.data.message)
              }
            });
        })
        .catch((_) => {});
    },
    getRoleList() {
      if (!this.roleList || this.roleList.length == 0) {
        this.$request.getrokist
          .getList({
            page: 1,
            size: 999999
          })
          .then((res) => {
            if (res && res.data.code == 200) {
              for (
                let index = 0;
                index < res.data.content.data.length;
                index++
              ) {
                const element = res.data.content.data[index];
                if (element.role_id != 3) {
                  this.roleList.push(element);
                }
              }
            }
          });
      }
    },
    inputKey(e) {
      if (e.code.indexOf("Enter") != -1) {
        this.getList(1);
      }
    },
    getList(page) {
      if (page) {
        this.form.page = page;
      }
      this.loading = true;
      this.$request.admin.getAdminUserList(this.form).then((res) => {
        this.loading = false;
        if (res && res.data.code == 200) {
          this.count = res.data.content.count;
          this.tableData = res.data.content.data;
        }
      });
    },
  },
};
</script>

<style lang="scss">
.page {
  width: 100%;
  padding: 20px;

  .btns {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: flex-start;
  }

  .input {
    width: 200px;
  }

  .avatar {
    width: 50px;
    height: 50px;
    border-radius: 50%;
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
  }
}
</style>